package com.zhutengwei.android.zuji.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Administrator on 2016/12/18.
 */
public class DbOpenHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static DbOpenHelper instance;

    private static final String USERS_TABLE_CREATE = "CREATE TABLE "
            + UserTable.TABLE_NAME + " ("
            + UserTable.COLUMN_NICKNAME + " TEXT PRIMARY　KEY, "
            + UserTable.COLUMN_ADDRESS + " TEXT, "
            + UserTable.COLUMN_EMAIL + " TEXT, "
            + UserTable.COLUMN_PHONENUM + " TEXT, "
            + UserTable.COLUMN_USERPASS + " TEXT, "
            + UserTable.COLUMN_AVATAR + " TEXT, "
            + UserTable.COLUMN_SIGNATURE + " TEXT, "
            + UserTable.COLUMN_REGISTERDATE + " TEXT);";

    private static final String ZUJI_TABLE_CREATE = "CREATE TABLE "
            + ZujiTable.TABLE_NAME + " ("
            + ZujiTable.COLUMN_ID + " INTEGER PRIMARY KEY NOT NULL , "
            + ZujiTable.COLUMN_EMAIL + " TEXT , "
            + ZujiTable.COLUMN_CATEGORY + " TEXT, "
            + ZujiTable.COLUMN_TITLE + " TEXT, "
            + ZujiTable.COLUMN_CONTENT + " TEXT, "
            + ZujiTable.COLUMN_LATITUDE + " TEXT, "
            + ZujiTable.COLUMN_LONGITUDE + " TEXT, "
            + ZujiTable.COLUMN_IMGDATA + " TEXT,"
            + ZujiTable.COLUMN_DATE + " TEXT);";

    //私有构造方法
    private DbOpenHelper(Context context, String name){
        super(context, name, null, DATABASE_VERSION);
    }

    //获取一个DbOpenHelper实例
    public static DbOpenHelper getInstance(Context context, String name){
        if(instance == null){
            instance = new DbOpenHelper(context.getApplicationContext(), name);
        }
        return instance;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建两张表
        db.execSQL(USERS_TABLE_CREATE);
        db.execSQL(ZUJI_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //TODO
    }

    //关闭数据库的instance
    public void closeDB(){
        if(instance != null){
            try{
                instance.getWritableDatabase().close();
            } catch (Exception e){
                e.printStackTrace();
            }
            instance = null;
        }
    }


}
